import React from 'react'
import {Row, Col, Button, Table, Select, Input, Switch, Avatar, Modal, message} from 'antd'
import Model from "./Model"
// import { UserOutlined } from '@ant-design/icons';
import '../styles.css'
import axios from "axios";
import api from "../../../api/api";
import Addcompany from "../../Organization/CompanyManagement";

const {Search} = Input;
const {Option} = Select;


class TenantAccountMaintenance extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            modelData: {
                title: "新增",
                visible: false,
                type: 1,//新增:1,编辑: 2,新增子:3
                gridList: {}
            },
            visible: false,
            gridList: {},
            data: [],
            inputValue: '',
            pageNum: 1,
            pageSize: 10,
            total: 0
        };
    }

    componentDidMount() {
        console.log("赋值");
        this.getTenantAccountMaintenanceList();
    }

    columns = [
        {
            title: 'ID',
            dataIndex: 'tenantId',
            className: "elementHidden",
            key: 'tenantId',
            width: '5%'
        },
        {
            title: '账号',
            dataIndex: 'tenantName',
            key: 'tenantName',
            width: '10%'
        },
        {
            title: '密码',
            dataIndex: 'tenantPassword',
            width: '10%',
            key: 'tenantPassword'
        },
        {
            title: '公司',
            dataIndex: 'tenantCompanyName',
            width: '10%',
            key: 'tenantCompanyName'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            width: '10%',
            key: 'createTime'
        },
        {
            title: '创建人',
            dataIndex: 'createUser',
            width: '10%',
            key: 'createUser'
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            width: '10%',
            key: 'updateTime'
        },
        {
            title: '更新人',
            dataIndex: 'updateUser',
            width: '10%',
            key: 'updateUser'
        },
        {
            title: 'GID',
            dataIndex: 'tenantGid',
            className: "elementHidden",
            key: 'tenantGid',
            width: '5%'
        },
        {
            title: '是否自动同步',
            dataIndex: 'isAutoSyn',
            key: 'isAutoSyn',
            width: '10%',
            render: (text, record, index) => {
                return(
                    <span><Switch className="btnRight" checked={record.isAutoSyn == 1 ? true:false} onClick={() => this.onIsAuto(record)}/></span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '10%',
            key: 'option',
            render: (text, record, index) => {
                return (
                    <span>
            <a className="optionMargin" onClick={() => this.onClickEdit(record)}>编辑</a>
            <a className="optionMargin" onClick={() => this.onClickDelete(record)}>删除</a>
          </span>
                )
            }
        }
    ];


    getTenantAccountMaintenanceList() {
        var that = this;
        axios.post(api.api_URL + "/admin/tenant/queryTenantInfoByPage?orgCode=" + localStorage.getItem('orgCode'), {
            "pageNum": this.state.pageNum,
            "pageSize": this.state.pageSize
        }, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            console.log(res.data)
            if (res.data.code != 1) {
                message.error({content: "加载失败，请重新尝试！"})
                return;
            }
            let totalSize = res.data.data.list.totalSize;
            const dataList = [];
            console.log(res.data.data.list.content)
            for (let i = 0; i < res.data.data.list.content.length; i++) {
                let resContent = res.data.data.list.content[i];

                const content = {};
                content.key = (i + 1);
                content.tenantId = resContent.tenantId;
                content.tenantName = resContent.tenantName;
                content.tenantPassword = resContent.tenantPassword;
                content.tenantCompanyName = resContent.tenantCompanyName;
                content.createTime = resContent.createTime;
                content.createUser = resContent.createUser;
                content.updateTime = resContent.updateTime;
                content.updateUser = resContent.updateUser;
                content.tenantGid = resContent.tenantGid;
                content.isAutoSyn = resContent.isAutoSyn;
                dataList[i] = content;
            }
            that.setState({
                data: dataList,
                total: totalSize
            })
        }).catch(function (err) {
            message.error({content: "加载失败，请重新尝试！"})
            console.log(err);
        });
    }

//分页
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getTenantAccountMaintenanceList()
        });

    }

    //新增
    onClickAdd() {
        this.setState({
            modelData: {
                title: "新增",
                type: 1,
                visible: true
            }
        }, () => {
            this.child.clearData()
        });
    }

    //编辑
    onClickEdit(item) {
        console.log("item", item)
        this.setState({
            modelData: {
                title: "编辑",
                type: 2,
                visible: true,
                gridList: item
            }
        }, () => {
            this.child.initEditData()
        });
    }

    //是否自动同步数据
    onIsAuto(item) {
        let that =this;
        console.log("item", item)
        axios({
            method: 'POST',
            url: api.api_URL + "/admin/tenant/isAutoSynTenantInfo",
            data: JSON.stringify(item),
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": "application/json;charset=UTF-8"
            },
        }).then(function (response) {
            if (response.data.code != 1) {
                message.error({content: "失败，请重新尝试 ！"})
                return;
            }
            message.success({content: "成功！"})
            that.refresh()
        })
            .catch(function (error) {
                message.error({content: "失败，请重新尝试 ！"})
                console.log(error);
            })
    }

//删除
    onClickDelete(item) {
        console.info("删除===", item);
        let that = this;
        let configModel = Modal.confirm({
            title: '删除',
            content: '是否确认删除？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    let url = api.api_URL + "/admin/tenant/deleteTenantInfo";
                    axios.post(url, {
                        tenantId: item.tenantId,
                        orgCode: localStorage.getItem('orgCode')
                    }, {
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": api.ContentType
                        }
                    }).then(function (res) {
                        if (res.data.code != 1) {
                            message.error({content: "删除失败，请重新尝试！"})
                            return;
                        }
                        message.success({content: "删除成功！"})

                        that.setState({
                            data: []
                        })
                        that.getTenantAccountMaintenanceList();
                        configModel.destroy();
                    }).catch(function (err) {
                        message.error({content: "删除失败，请重新尝试！"})

                        console.log(err);
                    })
                }).catch((e) => console.warn(e));

            },
            onCancel() {
            },
        })
    }

    onRef = (ref) => {
        this.child = ref
    }

    onclickSearch() {
        console.info("搜索");
        this.getTenantAccountMaintenanceList();
    }

    inputChange = (e) => {
        this.setState({
            inputValue: e.target.value
        })
    }

    onclickReset() {
        console.info("重置");
    }

    handleOk = e => {
        console.log(e);
        this.setState({
            modelData: {
                visible: false
            },
        });
    }
    handleCancel = e => {
        this.setState({
            modelData: {
                visible: false
            },
        }, () => {
            this.refresh()
        });
    }

    refresh() {
        this.getTenantAccountMaintenanceList()
    }




    render() {

        return (
            <div className="girdBg">
                <Row className="searchBox">
                    <Col span={18}>
                        {/*<Search style={{width: 200, marginLeft: 30}}*/}
                                {/*placeholder="请输入账号" onChange={this.inputChange}*/}
                        {/*/>*/}
                        {/*<Button type='primary' style={{marginLeft: 30}}*/}
                                {/*onClick={this.onclickSearch.bind(this)}>搜索</Button>*/}
                    </Col>
                    <Col icon={"save"} span={6} className="btnRight">
                        <Button type='primary' onClick={this.onClickAdd.bind(this)}>新增租户</Button>
                        {/*<Button shape='circle' type='primary' icon="download"/>*/}
                    </Col>
                </Row>
                <Row style={{margin: 30}}>
                    <Table
                        columns={this.columns}
                        dataSource={this.state.data}
                        scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                        columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                            const fun = () => ({style: {whiteSpace: 'nowrap'}});
                            item.onHeaderCell = fun;
                            item.onCell = fun;
                            return item;
                        })}
                        pagination={{
                            simple: false,
                            current: this.state.pageNum,
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            showTotal: (count = this.state.total) => {
                                return '共' + count + '条'
                            },
                            onChange: (current, pageSize) => {
                                this.onBaseClick(current, pageSize)
                            }
                        }}
                    />
                </Row>
                <Model data={this.state.modelData} handleCancel={this.handleCancel} refresh={this.refresh}
                       onRef={this.onRef}
                       history={this.props.history}/>
            </div>
        )
    }
}

export default TenantAccountMaintenance